package com.von.nhcf.mvc.interceptor;

import com.von.nhcf.constant.NhcfConstant;
import com.von.nhcf.entity.Admin;
import com.von.nhcf.exception.AccessIllegalException;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 拦截未登录就访问搜保护资源的请求
 * @author von
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) {
        // 通过 request 对象获取 Session 对象
        HttpSession session = request.getSession();
        // 尝试从 Session 域中获取 Admin 对象
        Admin admin = (Admin) session.getAttribute(NhcfConstant.ATTR_NAME_LOGIN_ADMIN);
        // 判断 admin 对象是否为空
        if(admin == null) {
        // 抛出异常
            throw new AccessIllegalException(NhcfConstant.MESSAGE_ACCESS_ILLEGAL);
        }
        // 如果 Admin 对象不为 null， 则返回 true 放行
        return true;
    }
}
